package com.zq.server.core.sevcice;


import static com.zq.common.constant.Constants.WX_LOGIN_USER_KEY;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;
import com.zq.common.config.Properties.TokenProperties;
import com.zq.common.constant.CacheConstants;
import com.zq.common.core.domain.model.WeChatLoginUser;
import com.zq.common.core.redis.RedisCache;
import com.zq.common.utils.ServletUtils;
import com.zq.common.utils.StringUtils;
import com.zq.common.utils.ip.AddressUtils;
import com.zq.common.utils.ip.IpUtils;
import com.zq.common.utils.uuid.IdUtils;

import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * token验证处理
 *
 * @author 财哥
 */
@Component
public class weChatTokenService {
    protected static final long MILLIS_SECOND = 1000;
    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
    private static final Logger log = LoggerFactory.getLogger(weChatTokenService.class);
    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;
    @Autowired
    private TokenProperties tokenProperties;
    @Autowired
    private RedisCache redisCache;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public WeChatLoginUser getWeChatUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(WX_LOGIN_USER_KEY);
                String userKey = getTokenKey(uuid);
                Object object = redisCache.getCacheObject(userKey);
                return  JSON.parseObject(String.valueOf(object), WeChatLoginUser.class);
            } catch (Exception e) {
                log.error("获取用户信息异常'{}'", e.getMessage());
            }
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setWeChatUser(WeChatLoginUser wxUser) {
        if (StringUtils.isNotNull(wxUser) && StringUtils.isNotEmpty(wxUser.getToken())) {
            refreshToken(wxUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delWeChatUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     * @param weChatLoginUser 用户信息
     * @return 令牌
     */
    public String createToken(WeChatLoginUser weChatLoginUser) {
        String token = IdUtils.fastUUID();
        weChatLoginUser.setToken(token);
        setUserAgent(weChatLoginUser);
        refreshToken(weChatLoginUser);
        //创建上下文
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(weChatLoginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        Map<String, Object> claims = new HashMap<>();
        claims.put(WX_LOGIN_USER_KEY, token);
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param weChatLoginUser
     * @return 令牌
     */
    public void verifyToken(WeChatLoginUser weChatLoginUser) {
        long expireTime = weChatLoginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(weChatLoginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param weChatLoginUser 登录信息
     */
    public void refreshToken(WeChatLoginUser weChatLoginUser) {
        weChatLoginUser.setLoginTime(System.currentTimeMillis());
        weChatLoginUser.setExpireTime(weChatLoginUser.getLoginTime() + tokenProperties.getWeChatExpireTime() * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(weChatLoginUser.getToken());
        redisCache.setCacheObject(userKey, weChatLoginUser, tokenProperties.getWeChatExpireTime(), TimeUnit.MINUTES);
    }

    /**
     * 设置用户代理信息
     *
     * @param wxUsers 登录信息
     */
    public void setUserAgent(WeChatLoginUser wxUsers) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr();
        wxUsers.setIpaddr(ip);
        wxUsers.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        wxUsers.setBrowser(userAgent.getBrowser().getName());
        wxUsers.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, tokenProperties.getWeChatSecret()).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(tokenProperties.getWeChatSecret())
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(tokenProperties.getWeChatHeader());
        if (StringUtils.isNotEmpty(token) && token.startsWith(CacheConstants.WECHAT_LOGIN_TOKEN_KEY)) {
            token = token.replace(CacheConstants.WECHAT_LOGIN_TOKEN_KEY, "");
            return token;
        } else {
            return null;
        }
    }

    private String getTokenKey(String uuid) {
        return CacheConstants.WECHAT_LOGIN_TOKEN_KEY + uuid;
    }
}
